package sunyu.service.impl;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sunyu.mapper.ShiroUserMapper;
import sunyu.mapper.ShiroUserRoleMapper;
import sunyu.pojo.ShiroUser;
import sunyu.pojo.ShiroUserRoleKey;
import sunyu.service.UserService;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 孙宇
 */
@Service("userService")
public class UserServiceImpl implements UserService {
    @Resource
    ShiroUserMapper shiroUserMapper;

    @Resource
    ShiroUserRoleMapper shiroUserRoleMapper;

    @Override
    @Transactional
    public void insertUserAndRole(ShiroUser record, List<String> roleIds) {
        shiroUserMapper.insert(record);

        if (roleIds != null && roleIds.size() > 0) {
            for (String id : roleIds) {
                ShiroUserRoleKey ur = new ShiroUserRoleKey();
                ur.setUser_id(record.getId());
                ur.setRole_id(id);
                shiroUserRoleMapper.insert(ur);
            }
        }
    }

    @Override
    @Transactional
    public void updateUserAndRole(ShiroUser record, List<String> roleIds) {
        shiroUserMapper.updateByPrimaryKey(record);

        Map params = new HashMap();
        params.put("user_id", record.getId());
        shiroUserRoleMapper.delete(params);

        if (roleIds != null && roleIds.size() > 0) {
            for (String id : roleIds) {
                ShiroUserRoleKey ur = new ShiroUserRoleKey();
                ur.setUser_id(record.getId());
                ur.setRole_id(id);
                shiroUserRoleMapper.insert(ur);
            }
        }
    }

    @Override
    public List<String> selectRoleIds(String userId) {
        Map params = new HashMap();
        params.put("user_id", userId);
        return shiroUserRoleMapper.selectRoleIds(params);
    }

    @Override
    public List<ShiroUser> select(Map params) {
        return shiroUserMapper.select(params);
    }

    @Override
    public int deleteByPrimaryKey(String id) {
        return shiroUserMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(ShiroUser record) {
        return shiroUserMapper.insert(record);
    }

    @Override
    public int insertSelective(ShiroUser record) {
        return shiroUserMapper.insertSelective(record);
    }

    @Override
    public ShiroUser selectByPrimaryKey(String id) {
        return shiroUserMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(ShiroUser record) {
        return shiroUserMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(ShiroUser record) {
        return shiroUserMapper.updateByPrimaryKey(record);
    }
}
